package com.xdap.common.util;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ProjectName gwm-plan-plugin
 * @Description
 * @Date 2023/9/27 9:20
 * @Author shangsheng.li
 **/
public class RateLimiter {
    private final int maxCallsPerSecond;
    private final AtomicInteger counter = new AtomicInteger(0);

    public RateLimiter(int maxCallsPerSecond) {
        this.maxCallsPerSecond = maxCallsPerSecond;
    }

    public synchronized boolean tryAcquire() {
        int currentCount = counter.getAndIncrement();
        if (currentCount > maxCallsPerSecond) {
            //超过了每秒限制，进行等待
            try {
                long waitTime = (long) (1.0 / maxCallsPerSecond * currentCount);
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                //处理中断异常
                Thread.currentThread().interrupt();
            }
            //重置计数器并获取新的当前值
            int newCount = counter.getAndSet(0);
            if (newCount > maxCallsPerSecond) {
                //仍然超过了每秒限制，继续等待
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            } else {
                //可以继续执行操作
                return true;
            }
        } else {
            //未超过每秒限制，直接返回true
            return true;
        }
        return false;
    }
}
